﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Portal.Web.Model;
using Portal.Cms.Model;
using Portal.Cms.Bussiness;
using Portal.Web.Utility;
using Portal.Core;
using Portal.Cms.Utility;
using Portal.Systems.Model;
using System.Data;
using System.Collections.ObjectModel;
using Portal.Sharepoint.Utility;
using System.Xml;
using Portal.Cpv.SystemSync.Service;

namespace Portal.Cms.Cpv.Render
{
    public class CpvSyncRenderBll
    {
        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam=WebEnvironments.CreateSiteParam(SiteId);

                
                string ButtonImage = WebConfig.GetButtonIconRoot(OSiteParam);
                string SyncText = "Hệ thống sẽ đồng bộ dữ liệu liên quan như nhóm người dùng, tài khoản truy cập, chuyên mục, định mức bài, định mức ảnh vv... Thời gian đồng bộ phụ thuộc vào dữ liệu và mạng và sẽ mất 1 ít thời gian chờ đợi...";
                string Html =
                   "<script language=javascript>\r\n" +
                   "    function CheckAllowSync()\r\n"+
                   "    {\r\n"+
                   "        SyncCategory=document.getElementById('chkCategory').checked;\r\n" +
                   "        SyncRoleAndUser=document.getElementById('chkRoleAndUser').checked;\r\n" +
                   "        SyncOtherNews=document.getElementById('chkDicNewsOther').checked;\r\n" +
                   "        if(SyncCategory==false && SyncRoleAndUser==false && SyncOtherNews==false)\r\n" +
                   "        {\r\n" +
                   "            alert('Chưa xác định phạm vi đồng bộ!');\r\n" +
                   "            return false;\r\n" +
                   "        }\r\n" +
                   "        return true;\r\n"+
                   "    }\r\n"+
                   "    function ClientSync()\r\n" +
                   "    {\r\n" +
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        if(CheckAllowSync()==false)return;\r\n"+
                   "        if(confirm('Bạn đã chắc chắn đồng bộ chưa?')==false)return;\r\n" +
                   "        document.getElementById('divProcessing').innerHTML='Tiến hành động dữ liệu...';\r\n" +
                   "        setTimeout('RealClientSync()',10);\r\n" +
                   "    }\r\n" +


                   "    function RealClientSync()\r\n" +
                   "    {\r\n" +
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        SyncCategory=document.getElementById('chkCategory').checked;\r\n"+
                   "        SyncRoleAndUser=document.getElementById('chkRoleAndUser').checked;\r\n" +
                   "        SyncOtherNews=document.getElementById('chkDicNewsOther').checked;\r\n" +
                   "        AjaxOut = Portal.Cms.Cpv.Render.CpvSyncRenderBll.ServerSideSync(SiteId, SyncCategory, SyncRoleAndUser, SyncOtherNews).value;\r\n" +
                   "        if(AjaxOut.Error)\r\n" +
                   "        {\r\n" +
                   "            document.getElementById('divProcessing').innerHTML='" + SyncText + "';\r\n" +
                   "            alert(AjaxOut.InfoMessage);\r\n" +
                   "            return;\r\n" +
                   "        }\r\n" +
                   "        document.getElementById('divProcessing').innerHTML='" + SyncText + "';\r\n" +
                   "        alert(AjaxOut.InfoMessage);\r\n" +
                   "    }\r\n" +


                   "</script>\r\n" +
                    "  <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n" +
                    "            <li onclick=\"javascript:ClientSync();\"><img class=image src=\"" + ButtonImage + "/Execute.png\"><div>Đồng bộ dữ liệu</div></li>\r\n" +
                    "            <li onclick=\"javascript:window.open('../../home.aspx','_self');\"><img class=image src=\"" + ButtonImage + "/back.png\"><div>Quay lại</div></li>\r\n" +
                    "        </ul>\r\n" +
                    "  </div>\r\n" +
                    "   <h3>Đồng bộ dữ liệu từ hệ thống</h3>\r\n" +
                    "   <div class=SyncContent>" +
                    "       <div id=divProcessing>" + SyncText + "</div>\r\n" +
                    "   </div>\r\n" +
                    "   <div class=SyncOption>\r\n" +
                    "       <table>\r\n"+
                    "           <tr>\r\n"+
                    "               <td style=\"width:20px;\"><input type=checkbox id=chkCategory></td>\r\n" +
                    "               <td>Chuyên mục tin</td>\r\n" +
                    "           </tr>\r\n"+
                    "           <tr>\r\n" +
                    "               <td><input type=checkbox id=chkRoleAndUser></td>\r\n" +
                    "               <td>Hệ thống tài khoản truy cập</td>\r\n" +
                    "           </tr>\r\n" +
                    "           <tr>\r\n" +
                    "               <td><input type=checkbox id=chkDicNewsOther></td>\r\n" +
                    "               <td>Các từ điển về mức tin bài, mức ảnh ..</td>\r\n" +
                    "           </tr>\r\n" +
                    "       </table>\r\n" +
                    "   </div>\r\n";
                    
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideSync(
            string SiteId, 
            bool SyncCategory, 
            bool SyncRoleAndUser, 
            bool SyncOtherNews)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string GroupDataId = (string)WebConfig.GetConfigFromXml(OSiteParam, "NewsGroupDataForAdd");
                DataLanguageCls[] DataLanguages = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingDataLanguage(SiteId);

                if (SyncCategory)
                {
                    for (int iIndexLanguage = 0; iIndexLanguage < DataLanguages.Length; iIndexLanguage++)
                    {
                        Collection<GroupDataCategoryCls> GroupDataCategories = new Collection<GroupDataCategoryCls> { };
                        
                        Collection<GroupDataCategoryCls>
                            SharePointGroupDataCategories = SPCategory.GetCategoryData(SiteId);
                        for (int iIndex = 0; iIndex < SharePointGroupDataCategories.Count; iIndex++)
                        {
                            SharePointGroupDataCategories[iIndex].frkGroupDataId = GroupDataId;
                        }

                        for (int iIndex = 0; iIndex < SharePointGroupDataCategories.Count; iIndex++)
                        {
                            if (SharePointGroupDataCategories[iIndex].frkGroupDataCategoryId.Equals("0") && SharePointGroupDataCategories[iIndex].frkDataLanguageId.Equals(DataLanguages[iIndexLanguage].DataLanguage))
                            {
                                GroupDataCategories.Add(SharePointGroupDataCategories[iIndex]);
                                for (int iSub = 0; iSub < SharePointGroupDataCategories.Count; iSub++)
                                {
                                    if (SharePointGroupDataCategories[iSub].frkGroupDataCategoryId.Equals(SharePointGroupDataCategories[iIndex].GroupDataCategoryId) && SharePointGroupDataCategories[iSub].frkDataLanguageId.Equals(DataLanguages[iIndexLanguage].DataLanguage))
                                    {
                                        GroupDataCategories[GroupDataCategories.Count - 1].SubGroupDataCategories.Add(SharePointGroupDataCategories[iSub]);
                                    }
                                }
                            }
                        }
                        CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).SyncGroupDataCategory(SiteId, GroupDataCategories);
                    }
                }

                if (SyncRoleAndUser)
                {
                    RoleCls[] Roles = ReadingGroupInSharepoint(SiteId);
                    new CpvSysSyncService().ExecuteSync(SiteId, Roles);
                }

                if (SyncOtherNews)
                {

                }

                OAjaxOut.InfoMessage = "Hoàn thành việc đồng bộ";
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }





        public static RoleCls[] ReadingGroupInSharepoint(string SiteId)
        {
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential("tntung", "slregis", "csoft");
            var group = SPServiceInstance.SharepointUserGroup(SiteId);

            List<RoleCls> lst = new List<RoleCls>();
            foreach (XmlNode node in group.GetGroupCollectionFromSite())
            {
                if (node.Name == "Groups")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "Group")
                        {
                            RoleCls role = new RoleCls();

                            string SharePointRoleId = node.ChildNodes[i].Attributes["Name"].Value;
                            role.RoleName = node.ChildNodes[i].Attributes["Name"].Value;
                            role.RoleId = System.Guid.NewGuid().ToString(); //;
                            role.RoleCode = node.ChildNodes[i].Attributes["ID"].Value;
                            role.Users = ReadingUserBelongRole(SiteId, SharePointRoleId, string.Empty);

                            lst.Add(role);
                        }
                    }
                }
            }

            return lst.ToArray();
        }

        public static UserCls[] ReadingUserBelongRole(string SiteId, string RoleId, string Keyword)
        {
            //RoleCls
            var group = SPServiceInstance.SharepointUserGroup(SiteId);
            List<UserCls> lst = new List<UserCls>();
            foreach (XmlNode node in group.GetUserCollectionFromGroup(RoleId))
            {
                if (node.Name == "Users")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "User")
                        {
                            UserCls user = new UserCls();
                            user.UserId = node.ChildNodes[i].Attributes["LoginName"].Value.Replace("\\", "$");
                            user.FullName = node.ChildNodes[i].Attributes["Name"].Value;
                            user.LoginName = node.ChildNodes[i].Attributes["LoginName"].Value;
                            lst.Add(user);
                        }
                    }
                }
            }

            return lst.ToArray();
        }
    }
}
